/*
 * *****************************************************************************
 *  Copyright ( c ) 2019 huibur Inc. All Rights Reserved.
 *
 *  This software is the confidential and proprietary information of Huibur Inc
 *  (*Confidential Information*). You shall not disclose such Confidential Information
 *  and shall use it only in accordance with the terms of the license agreement
 *  you entered into with Huibur or a Huibur authorized
 *  reseller (the "License Agreement*).
 *  ******************************************************************************
 */

package com.huibur.devicecheck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.huibur.devicecheck.enums.*;
import com.huibur.devicecheck.exception.UserDisableException;
import com.huibur.devicecheck.exception.UserNotFoundException;
import com.huibur.devicecheck.exception.UserNotPasswordException;
import com.huibur.devicecheck.mapper.*;
import com.huibur.devicecheck.model.param.DeviceParam;
import com.huibur.devicecheck.model.param.LoginParam;
import com.huibur.devicecheck.model.po.*;
import com.huibur.devicecheck.model.query.PwdQuery;
import com.huibur.devicecheck.model.vo.*;
import com.huibur.devicecheck.request.ObjRes;
import com.huibur.devicecheck.service.IForAppService;
import com.huibur.devicecheck.service.ITaskRecordDataService;
import com.huibur.devicecheck.utils.DateUtils;
import com.huibur.devicecheck.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/*******************************************************
* Title: ForAppServiceImpl.java
* Description:
* @author baiqingshuo
* @date 2021/9/24
* @version 1.0
*******************************************************/
@Service
public class ForAppServiceImpl implements IForAppService {

    @Autowired
    DeviceMapper deviceMapper;
    @Autowired
    TaskRecordMapper taskRecordMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    TaskMapper taskMapper;
    @Autowired
    CheckItemMapper checkItemMapper;
    @Autowired
    ITaskRecordDataService iTaskRecordDataService;
    @Autowired
    DeviceCategoryMapper deviceCategoryMapper;

    /**
     * 用户根据label获取设备详情
     * @param label
     * @return
     */
    @Override
    public AppVO selectDeviceByLabel(String label) {
        AppVO appVO = new AppVO();
        DeviceVO deviceVO = deviceMapper.selectDeviceByLabel(label);
        appVO.setDeviceVO(deviceVO);
        return appVO;
    }

    /**
     * 检修员登录
     * @param loginParam
     * @return
     */
    @Override
    public UserVO login(LoginParam loginParam) {
        UserPO userPO = userMapper.selectOne(new LambdaQueryWrapper<UserPO>()
                .eq(UserPO::getMobile, loginParam.getMobile())
                .ne(UserPO::getStatus, UserEnums.DELETE.getCode())
                .eq(UserPO::getRole, RoleEnums.CHECK.getCode()));
        if (null == userPO) {
            throw new UserNotFoundException();
        } else if (userPO.getStatus().equals(UserEnums.NORMAL.getCode())) {
            //用户存在，将密码进行MD5加密，与数据库进行碰撞
            String pwd = MD5Util.getMD5String(loginParam.getPassword());
            if (!pwd.equals(userPO.getPassword())) {
                throw new UserNotPasswordException();
            }
        } else if (userPO.getStatus().equals(UserEnums.DISABLE.getCode())) {
            throw new UserDisableException();
        }
        UserVO userVO = new UserVO();
        userVO.setAdminId(userPO.getAdminId());
        userVO.setRole(Long.valueOf(userPO.getRole()));
        userVO.setMobile(userPO.getMobile());
        userVO.setName(userPO.getName());
        userVO.setStatus(userPO.getStatus());
        userVO.setCreateAt(userPO.getCreateAt());
        return userVO;
    }

    /**
     * 新增巡检记录
     * @param recordVO
     * @return
     */
    @Override
    public ObjRes<Void> insertRecord(RecordVO recordVO) {
        UserPO userPO = userMapper.selectOne(new LambdaQueryWrapper<UserPO>()
                .eq(UserPO::getAdminId, recordVO.getAdminId())
                .eq(UserPO::getStatus, UserEnums.NORMAL.getCode()));    
        //获取每个月定时任务自动生成的任务
        TaskPO taskPO = taskMapper.selectOne(new LambdaQueryWrapper<TaskPO>()
                .eq(TaskPO::getStatus, TaskStatusEnums.IN_PROGRESS.getCode())
                .eq(TaskPO::getIsDeleted, TaskEnums.NORMAL.getCode()));
        TaskRecordPO taskRecordPO = new TaskRecordPO();
        taskRecordPO.setTaskId(taskPO.getId());
        taskRecordPO.setUserId(userPO.getAdminId());
        taskRecordPO.setDeviceLabel(recordVO.getLabel());
        taskRecordPO.setIsDeleted(TaskRecordEnums.NORMAL.getCode());
        taskRecordPO.setCreateAt(DateUtils.getCurrentTimestamp());
        taskRecordPO.setCreateBy(userPO.getAdminId());
        taskRecordPO.setRecord(recordVO.getRecord());
        taskRecordPO.setImage(recordVO.getImage());
        taskRecordPO.setStatus(recordVO.getStatus());
        taskRecordMapper.insert(taskRecordPO);

        List<TaskRecordDataPO> taskRecordDataPOList = new ArrayList<>();
        List<CheckDataVO> checkDataVOList = recordVO.getCheckDataVOList();
        for (CheckDataVO checkDataVO : checkDataVOList) {
            TaskRecordDataPO taskRecordDataPO = new TaskRecordDataPO();
            taskRecordDataPO.setTaskRecordId(taskRecordPO.getId());
            taskRecordDataPO.setCheckItemId(checkDataVO.getCheckItemId());
            taskRecordDataPO.setData(checkDataVO.getData());
            taskRecordDataPO.setCreateAt(DateUtils.getCurrentTimestamp());
            taskRecordDataPO.setCreateBy(userPO.getAdminId());
            taskRecordDataPOList.add(taskRecordDataPO);
        }
        iTaskRecordDataService.saveBatch(taskRecordDataPOList);

        return new ObjRes<Void>().success("创建成功");
    }

    /**
     * 修改密码
     * @param pwdQuery
     * @return
     */
    @Override
    public ObjRes<Void> updatePwd(PwdQuery pwdQuery) {
        UserPO userPo = userMapper.selectOne(new LambdaQueryWrapper<UserPO>()
                .eq(UserPO::getAdminId, pwdQuery.getAdminId())
                .eq(UserPO::getRole,RoleEnums.CHECK.getCode()));
        if (null == userPo) {
            return new ObjRes<Void>().error("用户不存在,请检查手机号是否正确");
        } else {
            String MD5OldPwd = MD5Util.getMD5String(pwdQuery.getNewPwd());
            String md5String = MD5Util.getMD5String(pwdQuery.getOldPwd());
            if (!userPo.getPassword().equals(md5String)) {
                return new ObjRes<Void>().error("旧密码输入错误，请重新输入");
            }
            if (userPo.getPassword().equals(MD5OldPwd)) {
                return new ObjRes<Void>().error("新密码不能与旧密码相同");
            } else {
                userPo.setPassword(MD5OldPwd);
                userMapper.updateById(userPo);
                return new ObjRes<Void>().success("修改成功");
            }
        }
    }

    /**
     * 任务列表
     * @return
     */
    @Override
    public List<TaskPO> taskList() {
        List<TaskPO> taskPOList = taskMapper.selectList(new LambdaQueryWrapper<TaskPO>()
                .ne(TaskPO::getIsDeleted, TaskEnums.DELETE.getCode()));
        if (CollectionUtils.isEmpty(taskPOList)) {
            return  new ArrayList<>();
        }

        List<TaskPO> collect = taskPOList.stream()
                .filter(e -> e.getActEndTime() == null || e.getStatus().equals(TaskStatusEnums.IN_PROGRESS.getCode()) || e.getActEndTime().getTime() <= DateUtils.getCurrentTimestamp().getTime())
                .collect(Collectors.toList());
        return collect;
    }

    /**
     * 检查项列表
     * @return
     */
    @Override
    public List<CheckItemPO> selectCheckItem(String label) {
        //根据设备唯一标识获取到设备名称
        DevicePO devicePO = deviceMapper.selectOne(new LambdaQueryWrapper<DevicePO>()
                .eq(DevicePO::getLabel, label)
                .eq(DevicePO::getIsDeleted, DeviceEnums.NORMAL.getCode()));
        Long deviceCategoryId = devicePO.getDeviceCategoryId();
        DeviceCategoryPO deviceCategoryPO = deviceCategoryMapper.selectOne(new LambdaQueryWrapper<DeviceCategoryPO>()
                .eq(DeviceCategoryPO::getId, deviceCategoryId)
                .eq(DeviceCategoryPO::getIsDeleted, 0));
        String deviceName = deviceCategoryPO.getName();
        //根据设备名称获取到检查项目中的参数配置
        List<CheckItemPO> checkItemPOList = checkItemMapper.selectList(new LambdaQueryWrapper<CheckItemPO>()
                .eq(CheckItemPO::getDeviceName, deviceName)
                .eq(CheckItemPO::getIsDeleted, 0));
        return checkItemPOList;
    }

    /**
     * 根据label修改设备信息
     * @param deviceParam
     * @return
     */
    @Override
    public ObjRes<Void> updateByLabel(DeviceParam deviceParam) {
        DevicePO device = deviceMapper.selectOne(new LambdaQueryWrapper<DevicePO>()
                .eq(DevicePO::getLabel, deviceParam.getLabel())
                .eq(DevicePO::getIsDeleted, DeviceEnums.NORMAL.getCode()));
        DevicePO devicePO = new DevicePO();
        devicePO.setId(device.getId());
        devicePO.setImage(deviceParam.getImage());
        devicePO.setUpdateAt(DateUtils.getCurrentTimestamp());
        devicePO.setUpdateBy(deviceParam.getAdminId());
        deviceMapper.updateById(devicePO);
        return new ObjRes<Void>().success("修改成功");
    }
}

